#include <REGX52.H>
#include <intrins.h>

sbit scl = P0^1;
sbit sda = P0^3;

void IIC_START(){
	
	scl = 0;
	scl = 1;
	sda = 1;
	_nop_();
	sda = 0;
	_nop_();
}

void IIC_STOP(){
	
	scl = 0;
	scl = 1;
	sda = 0;
	_nop_();
	sda = 1;
	_nop_();
	sda = 0;
}

void ICC_ACK(){

	char flag;
	sda = 1;
	_nop_();
	scl = 1;
	_nop_();
	flag= sda;
	_nop_();
	scl = 0;
}

void ICC_send_Btye(char datasend){

	int i = 0;
	
	for(i = 0;i < 8;i++){
		scl = 0;
		sda = datasend & 0x80;
		_nop_();
		scl = 1;
		_nop_();
		scl = 0;
		_nop_();
		datasend <<= 1;
	}
}



void OLED_Write_cmd(char cmd){
	
	IIC_START();
	ICC_send_Btye(0x78);
	ICC_ACK();
	ICC_send_Btye(0x00);
	ICC_ACK();
	ICC_send_Btye(cmd);
	ICC_ACK();
	IIC_STOP();
}

void OLED_Write_data(char datas){
	
	IIC_START();
	ICC_send_Btye(0x78);
	ICC_ACK();
	ICC_send_Btye(0x40);
	ICC_ACK();
	ICC_send_Btye(datas);
	ICC_ACK();
	IIC_STOP();
}

void OLED_Init(){
	
	OLED_Write_cmd(0xAE);//--display off
	OLED_Write_cmd(0x00);//---set low column address
	OLED_Write_cmd(0x10);//---set high column address
	OLED_Write_cmd(0x40);//--set start line address
	OLED_Write_cmd(0xB0);//--set page address
	OLED_Write_cmd(0x81); // contract control
	OLED_Write_cmd(0xFF);//--128
	OLED_Write_cmd(0xA1);//set segment remap
	OLED_Write_cmd(0xA6);//--normal / reverse
	OLED_Write_cmd(0xA8);//--set multiplex ratio(1 to 64)
	OLED_Write_cmd(0x3F);//--1/32 duty
	OLED_Write_cmd(0xC8);//Com scan direction
	OLED_Write_cmd(0xD3);//-set display offset
	OLED_Write_cmd(0x00);//
	OLED_Write_cmd(0xD5);//set osc division
	OLED_Write_cmd(0x80);//
	OLED_Write_cmd(0xD8);//set area color mode off
	OLED_Write_cmd(0x05);//
	OLED_Write_cmd(0xD9);//Set Pre-Charge Period
	OLED_Write_cmd(0xF1);//
	OLED_Write_cmd(0xDA);//set com pin configuartion
	OLED_Write_cmd(0x12);//
	OLED_Write_cmd(0xDB);//set Vcomh
	OLED_Write_cmd(0x30);//
	OLED_Write_cmd(0x8D);//set charge pump enable
	OLED_Write_cmd(0x14);//
	OLED_Write_cmd(0xAF);//--turn on oled panel
}

void OLED_Clear(){

	unsigned char i,j;
	
	for(i=0;i<8;i++){
		
		OLED_Write_cmd(0xB0 + i);//page0--page7
		//每个page从0列
		OLED_Write_cmd(0x00);
		OLED_Write_cmd(0x10);
		//0到127列，依次写入0，每写入数据，列地址自动偏移
		for(j = 0;j<128;j++){
			OLED_Write_data(0);
		}
	}
}

void main(){

	OLED_Init();

	OLED_Write_cmd(0x20);
	OLED_Write_cmd(0x02);
	OLED_Clear();
	//示例在左上角显示一个小方块
	OLED_Write_cmd(0xB0);
	OLED_Write_data(0x0F);
	OLED_Write_data(0x0F);
	OLED_Write_data(0x0F);
	OLED_Write_data(0x0F);
	OLED_Write_data(0x0F);
	OLED_Write_data(0x0F);
	OLED_Write_data(0x0F);
	while(1);
}
